#define JMBC_INSIDE
#include "slSound.h"
#include <Core/clCore.h>
#include <AL/al.h>
#include <stdio.h>

// Context

#define STORE ID_SMALL_STORE

static SLSound *store[STORE];

void
slSoundCreateContext(void)
{
	idClearStore(SLSound, STORE, store);
}

SLSound *
slSoundStore(unsigned int id)
{
	return store[id];
}

// Generation / Deletion

static
void
Init(SLSound *sound)
{
}

static
void
Term(SLSound *sound)
{
}

void
slGenSounds(unsigned int n, unsigned int *sounds)
{
	idGenObjects(SLSound, STORE, store, Init, n, sounds);
}

void
slDeleteSounds(unsigned int n, unsigned int *sounds)
{
	idDeleteObjects(store, Term, n, sounds);
}

// Load / Unload

void
slSoundUnload(unsigned int id)
{
	SLSound *sound;

	sound = store[id];

	free(sound->samples);
}

void
slSoundsUnload(unsigned int n, unsigned int *sounds)
{
	unsigned int i;

	for(i = 0; i < n; i++)
		slSoundUnload(sounds[i]);
}

// Query

ALenum
slSoundChannelsToFormat(unsigned int channels)
{
	ALenum format = AL_FORMAT_MONO16;

	switch(channels)
	{
		case 1: format = AL_FORMAT_MONO16; break;
		case 2: format = AL_FORMAT_STEREO16; break;
		default: elErrorSet(EL_ERROR_INVALID); break;
	}

	return format;
}

void
slSoundBufferData(unsigned int id, ALuint buffer)
{
	SLSound *sound;

	sound = store[id];

	alBufferData(buffer, slSoundChannelsToFormat(sound->channels), sound->samples, sound->frames * sound->channels * sizeof(short), sound->rate);
}
